<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { goodsItem, pageParams } from '../types/global'
import { getGuessLikeApi } from '../services/home'

onMounted(() => {
  getGuessLike()
})

const isFinished = ref(false),
  pagination: Required<pageParams> = { page: 1, pageSize: 10 },
  guessLikeList = ref<goodsItem[]>([]),
  getGuessLike = async () => {
    if (isFinished.value) return
    const { page, pageSize } = pagination
    const params = { page, pageSize }
    const res = await getGuessLikeApi(params)
    if (res.code) {
      const { page, pages, items } = res.result
      guessLikeList.value.push(...items)

      if (page < pages) pagination.page++
      else isFinished.value = true
    }
  }

const resetData = () => {
  pagination.page = 1
  guessLikeList.value = []
  isFinished.value = false
  getGuessLike()
}

defineExpose({ getGuessLike, resetData })
</script>

<template>
  <!-- 猜你喜欢 -->
  <view class="caption">
    <text class="text">猜你喜欢</text>
  </view>
  <view class="guess">
    <navigator
      class="guess-item"
      v-for="item in guessLikeList"
      :key="item.id"
      :url="`/pages/goods/goods?id=${item.id}`"
    >
      <image class="image" mode="aspectFill" :src="item.picture"></image>
      <view class="name"> {{ item.name }} </view>
      <view class="price">
        <text class="small">¥</text>
        <text>{{ item.price }}</text>
      </view>
    </navigator>
  </view>
  <view class="loading-text"> {{ isFinished ? '-我也是有底线的-' : '正在加载...' }} </view>
</template>

<style lang="scss">
@import '@/components/styles/GyhGuess.scss';
</style>
